import style from './style.module.less'
import { Button, Form, Input, message } from 'antd'
import React, { ChangeEvent, useState } from 'react'
import * as api from '../../services/api'
import { useHistory } from 'react-router-dom'

export default function UpdatePwd(props: any) {
  let token: string = props.token

  const limit: number = 10

  const history = useHistory()

  const [oldPwd, setOldPwd] = useState<string>('')
  const [newPwd, setNewPwd] = useState<string>('')

  function setOldPwdOnChange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setOldPwd(e.target.value)
    } else {
      setOldPwd(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`旧的密码长度不会超过${limit}个字符`)
    }
  }

  function setNewPwdOnChange(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setNewPwd(e.target.value)
    } else {
      setNewPwd(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`新的密码的长度不能超过${limit}个字符`)
    }
  }

  async function updatePwd() {
    try {
      let res = await api.updatePwd(token, oldPwd, newPwd)
      if (res.data.stat === 'ok') {
        history.push('/login')
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  return (
    <div className={style.formRight}>
      <p className={style.formTitle}>修改密码</p>
      <Form.Item>
        旧的密码:
        <Input
          className={style.formOldPwd}
          value={oldPwd}
          onChange={(event) => setOldPwdOnChange(event)}
        />
      </Form.Item>
      <Form.Item>
        新的密码:
        <Input
          className={style.formNewPwd}
          value={newPwd}
          onChange={(event) => setNewPwdOnChange(event)}
        />
      </Form.Item>
      <Form.Item>
        <Button type="primary" onClick={updatePwd}>
          修改密码
        </Button>
      </Form.Item>
    </div>
  )
}
